#!/bin/bash
set -e
export DEBIAN_FRONTEND=noninteractive

userConfPath="/etc/sftp-users.conf"
userConfFinalPath="/var/run/sftp-users.conf"

function createUser() {
    IFS=':' read -a param <<< $@
    user="${param[0]}"
    pass="${param[1]}"

    if [ "${param[2]}" == "e" ]; then
        chpasswdOptions="-e"
        uid="${param[3]}"
        gid="${param[4]}"
        dir="${param[5]}"
    else
        uid="${param[2]}"
        gid="${param[3]}"
        dir="${param[4]}"
    fi

    if [ -z "$user" ]; then
        echo "FATAL: You must at least provide a username."
        exit 1
    fi

    if $(cat /etc/passwd | cut -d: -f1 | grep -q "^$user:"); then
        echo "WARNING: User \"$user\" already exists. Skipping."
        return 0
    fi

    useraddOptions="--no-user-group"

    if [ -n "$uid" ]; then
        useraddOptions="$useraddOptions --non-unique --uid $uid"
    fi

    if [ -n "$gid" ]; then
        if ! $(cat /etc/group | cut -d: -f3 | grep -q "$gid"); then
            groupadd --gid $gid "group_$gid"
        fi

        useraddOptions="$useraddOptions --gid $gid -d /home/$user"
    fi

    useradd $useraddOptions $user

    if [ -n "$pass" ]; then
        echo "$user:$pass" | chpasswd $chpasswdOptions
    else
        usermod -p "*" $user # disabled password
    fi

    # Make sure dirs exists and has correct permissions
    if [ -n "$dir" ]; then
        IFS=',' read -a dirParam <<< $dir
        for dirPath in ${dirParam[@]}; do
            dirPath=/home/$user/$dirPath
            echo "Creating and/or setting permissions on $dirPath"
            mkdir -p $dirPath
            chown -R $user:users $dirPath
        done
    fi
}


# Create users only on first run
if [ ! -f "$userConfFinalPath" ]; then

    # Append users from arguments to final config
    for user in "$@"; do
        echo "$user" >> "$userConfFinalPath"
    done

    # Check that we have users in config
    if [ "$(cat "$userConfFinalPath" | wc -l)" == 0 ]; then
        echo "FATAL: No users provided!"
        printHelp
        exit 3
    fi

    # Import users from final conf file
    while IFS= read -r user || [[ -n "$user" ]]; do
        createUser "$user"
    done < "$userConfFinalPath"
fi

# Set ChallengeResponseAuthentication to true
grep -q "ChallengeResponseAuthentication" /etc/ssh/sshd_config && sed -i "/^[^#]*ChallengeResponseAuthentication[[:space:]]no.*/c\ChallengeResponseAuthentication yes" /etc/ssh/sshd_config || echo "ChallengeResponseAuthentication yes" >> /etc/ssh/sshd_config

# Only enable the keyboard-interactive auth method
echo "AuthenticationMethods keyboard-interactive" >> /etc/ssh/sshd_config

exec /usr/sbin/sshd -D -e

